<?php
if( $_GET['ajax'] )
{
	$task = (int)$_GET['check'];
	require( "./usersConfigs.php" );
	require("../sql/sqlCon.php");
	//error_reporting(0); // no error reporting as if something occurs it will break after-ajax error handling
	switch( $task )
	{
		case 1 : echo mailCheck($_POST['data']); break;
		case 2 : echo usernameCheck($_POST['data']); break;
		case 3 : echo passwordCheck($_POST['data']); break;
		default : break;
	}
}
else
{
	require( "./account/usersConfigs.php" );
	require( "./sql/sqlCon.php" );
}


function mailCheck($mail)
{
	if( !mailFormatCheck($mail) ) return 1;
	if( mailInUseCheck($mail) ) return 2;
	return 0;
}
function mailFormatCheck($email) 
{
	$isValid = true;
	$atIndex = strrpos($email, "@");
	if( is_bool($atIndex) && !$atIndex ) return 0;
	
	if( strlen($email) > 250 ) return 0;
	$domain = substr($email, $atIndex+1);
	$local = substr($email, 0, $atIndex);
	$localLen = strlen($local);
	$domainLen = strlen($domain);
	if( $localLen < 1 || $localLen > 64 ) return 0;
	if( $domainLen < 1 || $domainLen > 255 ) return 0;
	if( $local[0] == '.' || $local[$localLen-1] == '.' ) return 0;
	if( preg_match('/\\.\\./', $local) ) return 0;
	if( !preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain) ) return 0;
	if( preg_match('/\\.\\./', $domain) ) return 0;
	if( !preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)) )
	if( !preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) return 0;
	
	return 1; // valid
}
function mailInUseCheck($mail)
{
	global $usersExtendedTableName;
	$mail = mysql_real_escape_string($mail);
	$quer = mysql_query("SELECT email FROM $usersExtendedTableName WHERE email='$mail'");
	$result = mysql_fetch_array($quer);
	if( empty( $result['email'] ) ) return 0; // doesn't exist, all good
	return 1;
}



function usernameCheck($uname)
{
	if( $e = usernameFormatCheck($uname) ) return $e;
	if( usernameExistCheck($uname) ) return 3;
	return 0;
}
function usernameFormatCheck($uname)
{
	global $usernameMaxLength, $usernameMinLength;
	if( !$uname ) return 1;
	if( strlen($uname) > $usernameMaxLength || strlen($uname) < $usernameMinLength ) return 1;
	
	if( preg_replace("#[a-zA-Z]+[a-zA-Z0-9]*#", '', $uname) !='' ) return 2;
	return 0;
}
function usernameExistCheck($uname)
{
	global $usersTableName;
	$uname = mysql_real_escape_string($uname);
	$quer = mysql_query("SELECT userId FROM $usersTableName WHERE userName='$uname'");
	$result = mysql_fetch_array($quer);
	if( empty($result['userId']) ) return 0; // doesn't exist, all good
	return 1;
}

function passwordCheck($passw)
{
	global $passwordMaxLength, $passwordMinLength;
	if( strlen($passw) < $passwordMinLength || strlen($passw) > $passwordMaxLength ) return 1;
	return 0;
}

?>